//
//  EXObjectServer.m
//  CommonSpaces
//
//  Created by PH on 8.2.10.
//  Copyright 2010 Codesign. All rights reserved.
//

#import "EXObjectServer.h"
#import "EXRemoteKVInvoker.h"

#ifndef MB_IPHONE
@implementation EXObjectServer

- (id)initWithKeyValueStore:(NSObject<ORMKeyValueStore>*)_KVStore {
	if ((self = [super init])) {
		KVStore = [_KVStore retain];
		mapOfIDs = [[NSMutableDictionary alloc] init];
		cache = [[NSMutableDictionary alloc] init];
		//zombies = [[NSMutableArray alloc] init];
	}
	return self;
}

+ (EXObjectServer*)localServerWithServiceName:(NSString*)serviceName {
	id invoker = [NSConnection rootProxyForConnectionWithRegisteredName: serviceName host: nil];
	if (invoker != nil) return [[[self alloc] initWithKeyValueStore: invoker] autorelease];
	else return nil;
}

- (BOOL)serveWithServiceName:(NSString*)serviceName maximalNumberOfConnections:(NSUInteger)maximalNumberOfConnections {
	EXRemoteKVInvoker* invoker = [[EXRemoteKVInvoker alloc] initWithObject: KVStore withObject: self]; // memory leaks here (intentionally)
	id connection = [NSConnection serviceConnectionWithName: serviceName rootObject: invoker];
	if (connection != nil) {
		if (maximalNumberOfConnections > 1) [connection enableMultipleThreads];
		for (int i = 0; i < maximalNumberOfConnections; i++) [connection runInNewThread];
		return YES;
	}
	return NO;
}

- (void)dealloc {
	//
	[super dealloc];
}

@end
#endif